<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="searchData" layout="inline">
            <a-form-item label="组织排针名称" v-if="permissionStore.hasPermisson('zzpzlb.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="searchData.name"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHander"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :style="{ zIndex: 999 }"
      :mask-closable="false"
      height="100%"
      placement="bottom"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="saveData"
      :ok-loading="pageData.pageLoading"
      popup-container=".arco-tabs-content"
      @cancel="handleDrawerCancel"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>

      <a-space direction="vertical" fill>
        <a-form ref="formRef" layout="inline" :model="dataForm">
          <a-form-item
            label="名称"
            field="organizationName"
            :rules="[{ required: true, message: '名称必填' }]"
            :validate-trigger="['blur', 'change']"
          >
            <a-input class="bacClass" v-model="dataForm.organizationName" />
          </a-form-item>
          <a-form-item
            :style="{ width: '325px' }"
            label-col-flex="100px"
            label="设备机型"
            field="machineType"
            :rules="[{ required: true, message: '设备机型必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              :class="{ bacClass: true }"
              v-model="dataForm.machineType"
              @search="searchMachineTypeList"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusMachineTypeList"
            >
              <a-option v-for="item in pageData.machineTypeList" :value="item.typeName">
                {{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-form>

        <a-space>
          <span>设置排针列数</span
          ><input
            v-model="colNumber"
            type="number"
            style="width: 100px; border: 1px solid black"
            min="1"
            max="999"
          />
          <a-checkbox-group
            v-if="dataForm.machineType != '单面机'"
            v-model="alignState"
            :options="alignStateOptions"
            @change="alignStateChange"
          />
          <a-button size="small" type="primary" @click="addZhen">确定</a-button>
        </a-space>
        <div style="width: 100%; overflow: auto">
          <div style="white-space: nowrap">
            <span
              style="padding: 5px"
              v-if="dataForm.machineType != '单面机'"
              :style="{ 
                'margin-right': alignType == '3' ? '7.5px':'' ,
                }"
              >上排</span
              >
            <span style="padding: 5px" v-else>排针</span>
            <input
              @keyup="setNum(item)"
              v-for="(item, index) in sondatalist"
              :key="index"
              style="
                width: 30px;
                border: 1px solid black;
                padding: 5px;
                text-align: center;
                text-indent: 0;
              "
              :class="{ bacClass: true }"
              v-model="item.upBasin"
            />
          </div>
          <div style="white-space: nowrap" v-if="dataForm.machineType != '单面机'">
            <span
              style="padding: 5px"
              :style="{
                'padding-right': dataForm.machineType == '螺纹机' ? '35px' : '5px',
                'margin-right': alignType == '1' ? '15px' : (alignType == '2' ? '7.5px':''),
              }"
              >下排</span
            >

            <input
              @keyup="setNum1(item)"
              v-for="(item, index) in sondatalist"
              :key="index"
              :class="{ bacClass: true }"
              style="
                width: 30px;
                border: 1px solid black;
                padding: 5px;
                text-align: center;
                text-indent: 0;
              "
              v-model="item.belowBasin"
            />
          </div>
        </div>
        <a-form style="padding-top: 20px" ref="formRef" layout="inline" :model="dataForm">
          <a-form-item label="备注" field="remark">
            <a-textarea
              class="bacClass"
              placeholder=""
              style="width: 415px"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </a-space>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import { localeText } from '@/api/aggridZw'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { defineComponent, ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import usePermission from '@/store/modules/permission'
  
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  interface Firm {
    name: string
    id: number
  }

  interface GruopPzInfo {
    id: string | number
    // organizationCode: string
    organizationName: string
    remark: string
    upbelowBasin: string | number
    upBasin: string | number
    belowBasin: string | number
    pdGreyInformationId: string | number
    data: string | number
    list: any
    machineType: any
  }

  // 那dataFrom.data 的全局变量
  let sonid = ref()
  export default {
    name: 'GroupPZList',
    setup() {
      let cxbl = ''
      const selectHander = () => {
        page.value = 1
        cxbl = searchData.name
        doRefresh()
      }
      const table1Ref = ref<any>(null)
      const tableColumns = [
        {
          title: '序号',
          key: 'organizationCode',
          dataIndex: 'organizationCode',
          width: 150,
        },
        {
          title: '名称',
          key: 'organizationName',
          dataIndex: 'organizationName',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        // {
        //     title: "删除状态",
        //     key: "deleteState",
        //     dataIndex: "deleteState",
        //     width: 100,
        //     slotName: "deleteState",
        //     fixed: 'right'
        // },
        {
          title: '操作',
          key: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ]
      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                e: pageData.isEdit,
                a,
              }
            },
          }
        }

        return obj
      })
      tc.unshift({
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      })
      let configTable1 = {
        url: 'product/organizationPin/selectOrganizationPinPage', //接口路径
        queryData: {
          //接口参数
          deleteState: 0,
          organizationName: cxbl,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc,
        fileName: 'GroupPZList-1',
      }
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)

      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }

      function change1(val: any) {
        size.value = val
        doRefresh()
      }

      const headerShow = ref<boolean>(true)
      onMounted(() => {
        // 切换tap到本页面执行的方法
        emitter.on('GroupPZList', () => {
          // selCxAll({});
          doRefresh()
        })
      })
      const selOption = ref<any[]>([])
      const selHandler = (v: any) => {
        post({
          url: '/product/organizationPin/greyExtendValue',
          data: {
            organizationName: v,
            deleteState: '0',
          },
        }).then((result: any) => {
          if (result.code === 200) {
            selOption.value = result.data
          }
        })
      }
      const focusSel = (v: any) => {
        post({
          url: '/product/organizationPin/greyExtendValue',
          data: {
            organizationName: '',
            deleteState: '0',
          },
        }).then((result: any) => {
          if (result.code === 200) {
            selOption.value = result.data
          }
        })
      }

      function doRefresh() {
        table1Ref.value.setQuery({
          deleteState: 0,
          organizationName: cxbl,
        })
      }

      //单个排针修改查询
      function pzRefresh() {
        post({
          url: '/product/organizationPin/select',
          data: {
            id: dataForm.id,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              alignState.value = [String(data[0].alignState)]
              alignType.value = alignState.value[0]
              sondatalist.value = data
              colNumber.value = data.length
            }
          })
          .catch(console.log)
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const pagination2 = usePagination(doRefresh)
      const table = useTable()

      const rowKey = useRowKey('id')
      const tablediv = ref(null)
      const pageData = reactive<{
        gcList: Firm[]
        pageLoading: boolean
        showAdd: boolean
        sideTitle: string
        rHeight: number | undefined
        tablediv: any
        btnList: any[]
        isEdit: boolean
        machineTypeList: any[]
      }>({
        gcList: [],
        showAdd: false,
        sideTitle: '新增组织排针',
        rHeight: 0,
        tablediv: null,
        btnList: [],
        isEdit: false,
        pageLoading: false,
        machineTypeList: [],
      })
      const queryData = reactive({
        firm: '',
        clothType: '',
      })

      // 子表 上下排针请求回来的数据集合 响应式
      let sondatalist = ref<
        {
          id: number | string | null
          upBasin: string
          belowBasin: string
          pdOrganizationPinId: number | string
        }[]
      >([
        {
          id: null,
          upBasin: '',
          belowBasin: '',
          pdOrganizationPinId: '',
        },
      ])

      // 点击了新增
      const addHandler = () => {
        pageData.showAdd = true
        pageData.sideTitle = '新增组织排针'
        // 点击新增的时候 清空之前的编号数据
        // dataForm.organizationCode = ''
        // 点击新增的时候 清空之前的名称数据
        dataForm.organizationName = ''
        dataForm.remark = ''
        colNumber.value = 1
        // sondatalist.value = []
      }
      // 点击修改按钮
      const editHandler = (record: GruopPzInfo) => {
        dataForm.id = record.id
        // dataForm.organizationCode = record.organizationCode
        dataForm.organizationName = record.organizationName
        dataForm.remark = record.remark
        dataForm.machineType = record.machineType
        pageData.showAdd = true
        pageData.sideTitle = '修改组织排针'
        sessionStorage.setItem('组织排针', JSON.stringify(record.organizationName))

        pzRefresh()
        //tw加：排针规则
      }
      const searchData = reactive({
        code: '',
        name: '',
      })
      const searchData2 = reactive({
        code: '',
        name: '',
      })
      const dataForm = reactive<GruopPzInfo>({
        id: '',
        // organizationCode: '',
        organizationName: '',
        remark: '',
        upbelowBasin: '',
        upBasin: '',
        belowBasin: '',
        pdGreyInformationId: '',
        list: '',
        data: '',
        machineType: '',
      })
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
        // gridOption.value.sizeColumnsToFit();
      }
      // 新增组织排针的确定按钮
      const deleteHandler = () => {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          draggable: true,
          onOk() {
            pageData.pageLoading = true

            post({
              url: 'product/organizationPin/deleteList',
              data: table1Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '没有成功删除',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      // 子表格的+ 按钮 增加行列的
      const sondeleteHandler = () => {
        sondatalist.value.pop()
      }
      // 子表格的- 按钮 增加行列的
      const sonaddHandler = () => {
        let sonarr = { upBasin: '', belowBasin: '', id: '' }
      }
      const addZhen = () => {
        console.log('alignState.value[0]=>'+alignState.value[0]);
        alignType.value = alignState.value[0]
        if (colNumber.value == undefined || colNumber.value == '') {
          colNumber.value = 1
        }
        let n = colNumber.value - sondatalist.value.length
        if (n < 0) {
          for (let i = n; i < 0; i++) {
            sondatalist.value.pop()
          }
        } else if (n > 0) {
          for (let i = 0; i < n; i++) {
            sondatalist.value.push({
              upBasin: '',
              belowBasin: '',
              id: '',
              pdOrganizationPinId: '',
            })
          }
        } else {
          return
        }
      }
      const minsZhen = () => {
        if (sondatalist.value.length === 1) {
          Message.warning('至少保留一列')
          return
        }
        sondatalist.value.length = sondatalist.value.length - 1
      }
      // 新增要带的data
      const formRef = ref<FormInstance>()
      const saveData = () => {
        if (pageData.sideTitle == '修改组织排针') {
          post({
            url: '/product/organizationPin/update',
            // data: [{
            //     	"organizationName": dataForm.organizationName,
            //        "organizationCode": dataForm.organizationCode,
            //        "createTime": "",
            //           "id":dataForm.id,
            //        "createName": "",
            //       "deleteState": 0
            // }]
            data: [
              {
                id: dataForm.id,
                // organizationCode: dataForm.organizationCode,
                organizationName: dataForm.organizationName,
                remark: dataForm.remark,
                list: sondatalist.value,
                machineType: dataForm.machineType,
                alignState: alignState.value[0] ? Number(alignState.value[0]) : '',
              },
            ],
          }).then((result: any) => {
            if (result.code === 200) {
              handleDrawerCancel()

              sondatalist.value.length = 0
              Message.success('修改成功！')
              doRefresh()
            } else {
              Message.error(result.message)
            }
          })
          return
        }
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true
            if (sondatalist.value[0].upBasin == '' && sondatalist.value[0].belowBasin == '') {
              Message.error('排针必填')
              pageData.pageLoading = false
            } else {
              console.log('alignState', alignState.value[0])
              post({
                url: '/product/organizationPin/insert',
                data: {
                  id: dataForm.id,
                  // organizationCode: dataForm.organizationCode,
                  organizationName: dataForm.organizationName,
                  remark: dataForm.remark,
                  list: sondatalist.value,
                  machineType: dataForm.machineType,
                  alignState: alignState.value[0] ? Number(alignState.value[0]) : '',
                },
              }).then((result: any) => {
                if (result.code === 200) {
                  handleDrawerCancel()
                  // dataForm.organizationCode = ''
                  dataForm.organizationName = ''
                  dataForm.id = ''
                  sondatalist.value.length = 0
                  Message.success('保存成功！')
                  doRefresh()
                } else {
                  Message.error(result.message)
                }
              })
            }
            pageData.pageLoading = false
          }
        })
      }

      // 禁止input 只能输入整数
      function setNum(val: any) {
        if (val.upBasin === undefined || parseInt(val.upBasin) + '' === 'NaN') {
          val.upBasin = ''
        }
      }

      function setNum1(val: any) {
        if (val.belowBasin === undefined || parseInt(val.belowBasin) + '' === 'NaN') {
          val.belowBasin = ''
        }
      }

      const colNumber = ref<number>(1)
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('zzpzlb.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('zzpzlb.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('zzpzlb.sc')) {
        pageData.btnList.push('删除')
      }

      if (permissionStore.hasPermisson('zzpzlb.xg')) {
        pageData.isEdit = true
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        //flex: 1
      }
      const huiche = () => {
        page.value = 1
        cxbl = searchData.name
        doRefresh()
      }
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      const jitaileixing = (ob: any) => {
        if (ob == null || ob == undefined) {
          ob = ''
        }
        post({
          url: 'planSingle/machineType/getFieldValue',
          data: {
            typeName: ob,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            //pageData.machineTypeList = res.data
            pageData.machineTypeList = []
            res.data.map((o: any) => {
              pageData.machineTypeList.push({ typeName: o.typeName })
            })

            pageData.machineTypeList = Array.from(new Set(pageData.machineTypeList))
          }
        })
      }
      // 机型下拉框
      const focusMachineTypeList = () => {
        // getMachineTypeList({ machineName: "" })
        jitaileixing('')
      }
      const options: any = ref([])
      const loading = ref(false)
      // 机型下拉框
      const searchMachineTypeList = (value: any) => {
        if (value) {
          loading.value = true
          jitaileixing(value)
          options.value = pageData.machineTypeList
          loading.value = false
        } else {
          options.value = []
        }
      }
      const alignState = ref<any>(['0'])
      const alignStateOptions = [
        { label: '双面对针', value: '0' },
        { label: '螺纹对针', value: '1' },
        { label: '左对针', value: '2' },
        { label: '右对针', value: '3' },
      ]
      const alignStateChange = (val: any) => {
        if (val.length > 1) {
          const newChecked = val[1]
          alignState.value = [newChecked]
          val.splice(0, 1)
        }
      }
      const alignType = ref<any>('0')
      const handleDrawerCancel = () => {
        pageData.showAdd = false
        dataForm.organizationName = ''
        dataForm.id = ''
        sondatalist.value = [
          {
            id: null,
            upBasin: '',
            belowBasin: '',
            pdOrganizationPinId: '',
          },
        ]
        alignState.value = ['0']
        alignType.value = '0'
      }
      return {
        colState,
        options,
        loading,
        searchMachineTypeList,
        focusMachineTypeList,
        permissionStore,
        pagingList1,
        huiche,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        colNumber,
        setNum1,
        setNum,
        selOption,
        selHandler,
        focusSel,
        saveData,
        addZhen,
        tablediv,
        minsZhen,
        selectHander,
        searchData,
        searchData2,
        editHandler,
        deleteHandler,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        pagination2,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        sondeleteHandler,
        sonaddHandler,
        sondatalist,
        sonid,
        headerShow,
        handleChange,
        gridReady,
        table1Ref,
        configTable1,
        alignState,
        alignStateOptions,
        alignStateChange,
        alignType,
        handleDrawerCancel,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  .changerow {
    display: inline;
  }

  .pz {
    margin: 10px;
    // border: 1px solid #000;
    display: flex;
    justify-content: space-between;
  }
</style>
